Перехват текста сообщений

Редактировал(а) Alexandr Fokin 2023/01/05 20:56

Реализация перехвата сообщений, отправленных и полученных клиентом.
Также можно реализовать общую обертку над всеми клиентами, предоставляющую интерфейс перехвата

using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
 
namespace Test
{  
class MessageBehavior
  : IClientMessageInspector,
  IEndpointBehavior
 {
 public Action<string> OnSend { get; set; }
 public Action<string> OnReceive { get; set; }


 public void AddBindingParameters(
   ServiceEndpoint endpoint,
   BindingParameterCollection bindingParameters
   )
  {
  }

 public void ApplyClientBehavior(
   ServiceEndpoint endpoint,
   ClientRuntime clientRuntime
   )
  {
   clientRuntime
    .ClientMessageInspectors
    .Add(this);
  }

 public void ApplyDispatchBehavior(
   ServiceEndpoint endpoint,
   EndpointDispatcher endpointDispatcher
   )
  {
  }

 public void Validate(
   ServiceEndpoint endpoint
   )
  {
  }


 public object BeforeSendRequest(
  ref Message request,
   IClientChannel channel
   )
  {
   OnSend?.Invoke(
    request.ToString()
    );
  return null;
  }

 public void AfterReceiveReply(
  ref Message reply,
  object correlationState
   )
  {
   OnReceive?.Invoke(
    reply.ToString()
    );
  }  
 }

 
 static class Test
  {
  static void RunTest()
   {
   using (Service1Client client = new Service1Client())
    {
     client
      .Endpoint
      .EndpointBehaviors
      .Add(
        new MessageBehavior()
         {
          OnReceive = OnMsg,
          OnSend = OnMsg
         }
      );
   
    var res = client.GetData(123);
    }
   }
  }
}

ссылки:

WCF Client Request / Response Message Inspection
http://developereventlog.blogspot.com/2012/07/wcf-client-request-response-message.html

IClientMessageInspector Интерфейс
https://docs.microsoft.com/ru-ru/dotnet/api/system.servicemodel.dispatcher.iclientmessageinspector?view=dotnet-uwp-10.0

ClientRuntime Класс
https://docs.microsoft.com/ru-ru/dotnet/api/system.servicemodel.dispatcher.clientruntime?view=netframework-4.8

SoapHttpClientProtocol

Получение текста запросов из SoapHttpClientProtocol
https://habr.com/ru/post/337672/

Getting the raw SOAP XML sent via SoapHttpClientProtocol
https://orbinary.com/blog/2010/01/getting-the-raw-soap-xml-sent-via-soaphttpclientprotocol/

Теги: wcf